import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:getwidget/getwidget.dart';
import 'package:intl/intl.dart';
import 'package:nb_utils/nb_utils.dart';
import 'package:pitchertools/common/extensions/datetime_extension.dart';
import 'package:pitchertools/dao/data_manager.dart';
import 'package:pitchertools/http/dio_http.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';
import 'package:velocity_x/velocity_x.dart';

import '../../../../models/fans_query_bean.dart';
import '../../index.dart';

class AddQueryFansMsgDialog extends GetView<QueryFansController> {
  AddQueryFansMsgDialog({super.key}) {}

  final controller = Get.find<QueryFansController>();

  final TextEditingController csNumberTEC = TextEditingController();
  final TextEditingController startDateTEC = TextEditingController(
      text: DateTime.now().startOfToday().formatDateYYMMDD_HHMMSS());
  final TextEditingController endDateTEC = TextEditingController(
      text: DateTime.now().endOfToday().formatDateYYMMDD_HHMMSS());
  final DateRangePickerController dateRangePC = DateRangePickerController();

  /// 构建下拉菜单
  buildDropdownMenuItems() {
    List fansQueryApiMsgs = controller.state.fansQueryApiMsgsRx.value;
    var selectedFansQueryApiMsg = controller.state.selectedFansQueryApiMsg;

    // print(fansQueryApiList);

    List<DropdownMenuItem> dropdownMenuItems = [];

    for (var i = 0; i < fansQueryApiMsgs.length; i++) {
      var item = DropdownMenuItem(
        value: fansQueryApiMsgs[i],
        child: Text(fansQueryApiMsgs[i]['queryApiName']),
      );
      dropdownMenuItems.add(item);
    }

    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black, width: 1.0),
        borderRadius: BorderRadius.circular(4.0),
      ),
      child: DropdownButton(
        value: selectedFansQueryApiMsg['queryApiName'] == null
            ? null
            : selectedFansQueryApiMsg,
        onChanged: (newValue) {
          //设置查询api
          controller.state.selectedFansQueryApiMsg = newValue;
          print(newValue);
        },
        items: dropdownMenuItems,
        hint: const Text("请选择查询类型"),
        underline: Container(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('新增查询(可批量)').center(),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          //设置间隔为8
          children: [
            15.heightBox,
            TextField(
              controller: csNumberTEC,
              maxLines: null,
              decoration: const InputDecoration(
                border: OutlineInputBorder(
                  borderSide: BorderSide(width: 1, color: Colors.grey),
                ),
                contentPadding:
                    EdgeInsets.symmetric(horizontal: 3, vertical: 5),
                labelText: "客服号(一行一个)",
              ),
            ),
            10.heightBox,
            Obx(() => buildDropdownMenuItems()),
            10.heightBox,
            SizedBox(
              height: 250,
              width: 250,
              child: SfDateRangePicker(
                view: DateRangePickerView.month,
                selectionMode: DateRangePickerSelectionMode.range,
                initialSelectedRange: PickerDateRange(
                    DateTime.now().startOfToday(), DateTime.now().endOfToday()),
                controller: dateRangePC,
                onSelectionChanged: (dateRangePickerSelectionChangedArgs) {
                  if (dateRangePickerSelectionChangedArgs.value
                      is PickerDateRange) {
                    PickerDateRange pickerDateRange =
                        dateRangePickerSelectionChangedArgs.value;

                    if (pickerDateRange.startDate == null) {
                      startDateTEC.text = "";
                    } else {
                      startDateTEC.text =
                          pickerDateRange.startDate!.formatDateYYMMDD_HHMMSS();
                    }
                    if (pickerDateRange.endDate == null) {
                      endDateTEC.text = "";
                    } else {
                      endDateTEC.text = pickerDateRange.endDate!
                          .endOfToday()
                          .formatDateYYMMDD_HHMMSS();
                    }
                  }
                },
              ),
            ),
            10.heightBox,
            GFTextField(
              controller: startDateTEC,
              decoration: const InputDecoration(
                border: OutlineInputBorder(
                  borderSide: BorderSide(width: 1, color: Colors.grey),
                ),
                contentPadding:
                    EdgeInsets.symmetric(horizontal: 3, vertical: 1),
                labelText: "开始时间",
              ),
            ),
            10.heightBox,
            GFTextField(
              controller: endDateTEC,
              decoration: const InputDecoration(
                border: OutlineInputBorder(
                  borderSide: BorderSide(width: 1, color: Colors.grey),
                ),
                contentPadding:
                    EdgeInsets.symmetric(horizontal: 3, vertical: 1),
                labelText: "结束时间",
              ),
            ),
          ],
        ),
      ),
      actions: <Widget>[
        TextButton(
          child: const Text('确定'),
          onPressed: () async {
            // 获取客服号

            List<String> csNumberList = csNumberTEC.text.split("\n");

            String startDateStr = startDateTEC.text.trim();
            String endDateStr = endDateTEC.text.trim();

            //判断startDateStr和endDateStr是否可以正常转换为时间
            DateTime? startDate = DateTime.tryParse(startDateStr);
            DateTime? endDate = DateTime.tryParse(endDateStr);

            if (startDate == null || endDate == null) {
              SmartDialog.showToast("开始时间或结束时间格式不正确");
              return;
            }

            print(csNumberList);
            print(csNumberList.length);

            if (csNumberList.isEmpty ||
                startDateStr.isEmpty ||
                endDateStr.isEmpty) {
              SmartDialog.showToast("客服号、开始时间、结束时间不能为空");
              return;
            }

            // 获取设置的查询api
            var selectedFansQueryApi = controller.state.selectedFansQueryApiMsg;

            if (selectedFansQueryApi['queryApiName'] == null) {
              SmartDialog.showToast("请选择查询类型");
              return;
            }
            List<FansQueryBean> addData = [];
            for (var i = 0; i < csNumberList.length; i++) {
              var csNumber = csNumberList[i].trim();
              if (csNumber.isEmpty) {
                continue;
              }
              var fansQueryBean = FansQueryBean(
                csNumber: csNumber,
                queryApiType: selectedFansQueryApi['queryApiType'] == "HaiWang"
                    ? FansQueryApiType.HaiWang
                    : FansQueryApiType.DaMai,
                queryApiUrl: selectedFansQueryApi['queryApiUrl'],
                queryApiName: selectedFansQueryApi['queryApiName'],
                startDate: startDateStr,
                endDate: endDateStr,
              );
              addData.add(fansQueryBean);
            }
            controller.state.fansQueryBeanListRx.addAll(addData);

            SmartDialog.showToast("新增成功");
            Navigator.of(context).pop();
          },
        ),
        TextButton(
          child: const Text('取消'),
          onPressed: () async {
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  }
}
